﻿using Microsoft.AspNetCore.Cors;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.Auditing;
using Volo.Abp;
using Volo.Abp.Modularity;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc.AntiForgery;
using Newtonsoft.Json.Converters;
using Kstopa.WebApi.Core.Extensions;
using Volo.Abp.AspNetCore.Serilog;
using Volo.Abp.Autofac;
using Microsoft.OpenApi.Models;
using Volo.Abp.Swashbuckle;
using Kstopa.WebApi.Application;
using Kstopa.Sqlsugar;
using Volo.Abp.BackgroundJobs.Hangfire;
using Hangfire;
using Hangfire.MySql;
using Kstopa.Sqlsugar.Abstractions;
using System.Diagnostics;

namespace Kstopa.WPF.WebApi;

[DependsOn(
        typeof(AbpSqlSugarCoreModule),
        typeof(AbpApplicationModule),
        typeof(AbpAspNetCoreMvcModule),
        typeof(AbpAutofacModule),
        typeof(AbpSwashbuckleModule),
        typeof(AbpAspNetCoreSerilogModule),
        typeof(AbpAuditingModule),
         typeof(AbpBackgroundJobsHangfireModule)
        //typeof(AbpAspNetCoreAuthenticationJwtBearerModule),
        //typeof(YiFrameworkAspNetCoreModule)

        )]

public class Startup:AbpModule
{
    private const string DefaultCorsPolicyName = "Default";
    public override Task ConfigureServicesAsync(ServiceConfigurationContext context)
    {
        var configuration = context.Services.GetConfiguration();
        var host = context.Services.GetHostingEnvironment();
        var service = context.Services;

        //请求日志
        Configure<AbpAuditingOptions>(optios =>
        {
            optios.IsEnabled = true;
            optios.AlwaysLogSelectors.Add(x => Task.FromResult(true));
        });

        //动态Api
        Configure<AbpAspNetCoreMvcOptions>(options =>
        {
            options.ConventionalControllers.Create(typeof(AbpApplicationModule).Assembly, options => options.RemoteServiceName = "default");
            //options.ConventionalControllers.Create(typeof(YiFrameworkRbacApplicationModule).Assembly, options => options.RemoteServiceName = "rbac");
            //options.ConventionalControllers.Create(typeof(YiFrameworkBbsApplicationModule).Assembly, options => options.RemoteServiceName = "bbs");
        });

        //设置api格式
        service.AddControllers().AddNewtonsoftJson(options =>
        {
            options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            options.SerializerSettings.Converters.Add(new StringEnumConverter());
        });

        Configure<AbpAntiForgeryOptions>(options =>
        {
            options.AutoValidate = false;
        });

        //Swagger
        context.Services.AddYiSwaggerGen<Startup>(options =>
        {
            options.SwaggerDoc("default", new OpenApiInfo { Title = "Yi.Framework.Abp", Version = "v1", Description = "集大成者" });
        });


        context.Services.AddHangfire(config =>
        {
            config.UseStorage( new MySqlStorage(configuration["DbConnOptions:Url"],
                new MySqlStorageOptions
                {
                    QueuePollInterval = TimeSpan.FromSeconds(15),
                    JobExpirationCheckInterval = TimeSpan.FromHours(1),
                    CountersAggregateInterval = TimeSpan.FromMinutes(5),
                    PrepareSchemaIfNecessary = true
                }
                ));
        });
        //跨域
        context.Services.AddCors(options =>
        {
            options.AddPolicy(DefaultCorsPolicyName, builder =>
            {
                builder
                    .WithOrigins(
                        configuration["App:CorsOrigins"]!
                            .Split(";", StringSplitOptions.RemoveEmptyEntries)
                            .Select(o => o.RemovePostFix("/"))
                            .ToArray()
                    )
                    .WithAbpExposedHeaders()
                    .SetIsOriginAllowedToAllowWildcardSubdomains()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
            });
        });

        //jwt鉴权
        //var jwtOptions = configuration.GetSection(nameof(JwtOptions)).Get<JwtOptions>();
        //context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        //    .AddJwtBearer(options =>
        //    {
        //        options.TokenValidationParameters = new TokenValidationParameters
        //        {
        //            ClockSkew = TimeSpan.Zero,
        //            ValidateIssuer = true,
        //            ValidateAudience = true,
        //            ValidateLifetime = true,
        //            ValidateIssuerSigningKey = true,
        //            ValidIssuer = jwtOptions.Issuer,
        //            ValidAudience = jwtOptions.Audience,
        //            RequireExpirationTime = true,
        //            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.SecurityKey))
        //        };
        //        options.Events = new JwtBearerEvents
        //        {
        //            OnMessageReceived = context =>
        //            {
        //                var accessToken = context.Request.Query["access_token"];
        //                if (!string.IsNullOrEmpty(accessToken))
        //                {
        //                    context.Token = accessToken;
        //                }
        //                return Task.CompletedTask;
        //            }
        //        };
        //    });

        //授权
        context.Services.AddAuthorization();
        return Task.CompletedTask;
    }

    public override Task OnApplicationInitializationAsync(ApplicationInitializationContext context)
    {
        var service = context.ServiceProvider;

        var env = context.GetEnvironment();
        var app = context.GetApplicationBuilder();

        app.UseRouting();

        //跨域
        app.UseCors(DefaultCorsPolicyName);

        //鉴权
       // app.UseAuthentication();

        //swagger
        app.UseYiSwagger();
        //hangfire
        app.UseHangfireDashboard();
        BackgroundJob.Enqueue(() => Debug.WriteLine("Hello world from Hangfire!"));
        //请求处理
        // app.UseYiApiHandlinge();

        //静态资源
        app.UseStaticFiles("/api/app/wwwroot");
        app.UseDefaultFiles();
        app.UseDirectoryBrowser("/api/app/wwwroot");

        //工作单元
        app.UseUnitOfWork();

        //授权
        app.UseAuthorization();

        //审计日志
        app.UseAuditing();

        //日志记录
        app.UseAbpSerilogEnrichers();

        //终节点
        app.UseConfiguredEndpoints();

        return Task.CompletedTask;
    }
}
